package com.example.a1.fannong.core.http;

import android.support.compat.BuildConfig;

import com.example.a1.fannong.core.Config;
import com.example.a1.fannong.core.app.Logger;
import com.example.a1.fannong.core.app.MyApplication;
import com.example.a1.fannong.core.manager.user.UserManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.Map;

import cn.personal.library.http.AsyncHttpClient;
import cn.personal.library.http.OnProgressListener;
import cn.personal.library.http.StringResponseHandler;

/**
 * 基本的HTTP请求, 所有的HTTP请求都通过该类发起
 */
public abstract class HttpRequester {
    protected static Logger logger = new Logger("WEB");
    private StringResponseHandler responseHandler = new StringResponseHandler() {
        @Override
        public void onResult(int code, String content) {
            if (BuildConfig.DEBUG)
                logger.i("%s    %d    %s", getServiceName().getDescription(), code, content.trim());

            try {
                if (code == HttpURLConnection.HTTP_OK) {
                    JSONObject jsonObject = new JSONObject(content);
                    int state = jsonObject.optInt("state", 0);
                    String msg = jsonObject.optString("msg", "服务器未返回msg字段");
                    HttpRequester.this.onFinish(state, msg, jsonObject);
                } else {
                    if (BuildConfig.DEBUG) {
                        HttpRequester.this.onFinish(OnResultListener.RESULT_SERVER_CODE_ERROR, content == null ? "服务器开小差了，请稍后再试" : content, null);
                    } else {
                        HttpRequester.this.onFinish(OnResultListener.RESULT_SERVER_CODE_ERROR, "服务器开小差了，请稍后再试", null);
                    }
                }

            } catch (JSONException e) {
                e.printStackTrace();
                HttpRequester.this.onFinish(OnResultListener.RESULT_FAILED, e.getMessage(), null);
            }
        }

        @Override
        public void onError(Exception exception) {
            exception.printStackTrace();
            HttpRequester.this.onFinish(OnResultListener.RESULT_NET_ERROR, "网络不给力", null);
        }
    };

    public HttpRequester() {
    }

    /**
     * 返回服务器地址
     */
    protected String getUrl() {
        return Config.baseUrl;
    }


    /**
     * 放入请求参数  注意：公共参数已经放入
     */
    protected abstract void onPutParams(Map<String, Object> params);

    /**
     * 放入基本参数
     */
    protected void putParams(Map<String, Object> params) {
        String userId = MyApplication.getInstance().getManager(UserManager.class).getUid();
        if(!userId.equals("")){
            params.put("userId",userId );
        }
        onPutParams(params);
    }

    protected abstract ServiceName getServiceName();

    /**
     * 请求完成的回调，不管这样，都会有结果
     *
     * @param code 状态   200表示请求成功，其他的参考接口定义
     * @param msg  服务器返回的msg字段，，如果请求发生异常，该值为：网络不给力
     * @param data 服务器返回的数据，可能为null，需要的state进行判断
     */
    protected abstract void onFinish(int code, String msg, JSONObject data);

    /**
     * 发起get请求
     */
    public void doGet() {
        String url = getUrl() + getServiceName().getValue();
        Map<String, Object> params = new HashMap<>();
        putParams(params);

        if (BuildConfig.DEBUG)
            logger.i("GET %s    %s?%s", getServiceName().getDescription(), url, AsyncHttpClient.changeParams(params));

        AsyncHttpClient.get(url, params, responseHandler);
    }


    /**
     * 上传文件请求
     */
    public void upLoadFile(File file) {
        String url = getUrl() + getServiceName().getValue();
        Map<String, Object> params = new HashMap<>();
        putParams(params);
        if (params != null && params.size() > 0) {
            url = url + "?" + AsyncHttpClient.changeParams(params);
        }
        if (BuildConfig.DEBUG)
            logger.i("GET %s    %s?%s", getServiceName().getDescription(), url, AsyncHttpClient.changeParams(params));

        AsyncHttpClient.uploadFile(url, file, responseHandler, new OnProgressListener() {
            @Override
            public void onProgressChange(int length, int progress) {

            }
        });
    }

    public void doGet(int delay) {
        MyApplication.HANDLER.postDelayed(new Runnable() {
            @Override
            public void run() {
                doGet();
            }
        }, delay);
    }

    public void doGetDelay() {
        doGet(500);
    }

    public void doPost(int delay) {
        MyApplication.HANDLER.postDelayed(new Runnable() {
            @Override
            public void run() {
                doPost();
            }
        }, delay);
    }

    public void doPostDelay() {
        doPost(500);
    }

    /**
     * 发起Post请求
     */
    public void doPost() {
        String url = getUrl() + getServiceName().getValue();
        Map<String, Object> params = new HashMap<>();
        putParams(params);

        if (BuildConfig.DEBUG)
            logger.i("POST %s    %s?%s", getServiceName().getDescription(), url, AsyncHttpClient.changeParams(params));
        AsyncHttpClient.post(url, params, responseHandler);
    }


    /**
     * 发起Post请求
     */
    public void doPostJson() {
        String url = getUrl() + getServiceName().getValue();
        Map<String, Object> params = new HashMap<>();
        putParams(params);

        if (BuildConfig.DEBUG)
            logger.i("POST %s    %s?%s", getServiceName().getDescription(), url, AsyncHttpClient.changeParams(params));
        AsyncHttpClient.postJson(url, params, responseHandler);
    }


//   http://stlife.isum.cn/carwash/app/user/sendSmsCode?uid=1483160343722&type=1&mobileNo=15985141406
//   http://stlife.isum.cn/carwash/app/user/sendSmsCode?mobileNo=18805194711&type=0&uid=”20161221”
}
